﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using Newtonsoft.Json;

using CE.HotelEan;
using HotelWS;
using CE.Expedia;
using CE.Database;

public partial class travel_hotels_booking_book : System.Web.UI.Page
{
    HotelWS.HotelServicesImplService hws = new HotelWS.HotelServicesImplService();
    HotelBookingWS.HotelServicesImplService hbookingws = new HotelBookingWS.HotelServicesImplService();

    private string _apikey = "98pndgasdzzxpugjzqpxw6za";
    private int _minorrev = 13;
    private Int64 _cid = 381988;

    private string _ratekey = "";
    private string _suppliertype = "";
    private bool _isPayAtHotel = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["hid"] != null && Request.QueryString["rcode"] != null && Request.QueryString["rtype"] != null
            && Request.QueryString["rkey"] != null && Session["hotelsearchid"] != null && Session["customerSessionId"] != null)
        {
            GetHotelDetails();
            GetGuestDetails();
            GetRoomAvailability();
        }
        else
        {
            Response.Redirect("../hotels-search.aspx");
        }

        if (!Page.IsPostBack)
        {
            //fill card expiry year
            int _year;
            int startyear = CE.Global.General.GetUTCDateTime().Year;
            int endyear = CE.Global.General.GetUTCDateTime().Year + 10;
            for (_year = endyear; _year >= startyear; _year--)
            {
                ddlYearExpiration.Items.Insert(0, new ListItem(_year.ToString("0000"), _year.ToString("00")));
            }
            ddlYearExpiration.Items.Insert(0, new ListItem("- Year -", "-1"));

            FillCountryList();
            btnReserve.Attributes.Add("onclick", "javascript: if ( Page_ClientValidate() ){" + btnReserve.ClientID + ".disabled=true;}" + ClientScript.GetPostBackEventReference(btnReserve, ""));

        }
    }

    private void FillCountryList()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtList = new DataTable("ExpCountryList");
        string _spName = "sprocExpediaCountryListSelectAll";
        SortedList _sPara = new SortedList();

        _dtList = _db.GetDataTableBySP(_spName, _sPara);


        if (_dtList.Rows.Count > 0)
        {
            for (int i = 0; i < _dtList.Rows.Count; i++)
            {
                ddlCountry.Items.Insert(0, new ListItem(_dtList.Rows[i]["CountryName"].ToString(), _dtList.Rows[i]["CountryCode"].ToString()));
            }
        }
        else
        {
            ddlCountry.Items.Insert(0, new ListItem("Singapore", "SG"));
        }



    }

    protected void GetHotelDetails()
    {
        HotelInformationRequest hotelreq = new HotelInformationRequest();
        hotelreq.apiKey = _apikey;
        hotelreq.cid = _cid;
        hotelreq.minorRev = _minorrev;
        hotelreq.customerIpAddress = Request.UserHostAddress;
        hotelreq.customerUserAgent = Request.Browser.ToString();
        hotelreq.customerSessionId = Session["customerSessionId"].ToString();
        hotelreq.currencyCode = "SGD";
        hotelreq.hotelId = Convert.ToInt64(Request.QueryString["hid"].ToString());

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/info?cid=" + hotelreq.cid
                + "&minorRev=26&apiKey=" + hotelreq.apiKey
                + "&locale=" + hotelreq.locale
                + "&currencyCode=" + hotelreq.currencyCode
                + "&customerIpAddress=" + hotelreq.customerIpAddress
                + "&customerUserAgent=" + hotelreq.customerUserAgent
                + "&_type=xml&customerSessionId=" + hotelreq.customerSessionId
                + "&xml="
                + "<HotelInformationRequest><hotelId>" + hotelreq.hotelId +
                "</hotelId>";

        getData += "</HotelInformationRequest>";

        CXHotelInfo hotelresp = new CXHotelInfo();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
        {
            item.AppendChild(doc.CreateNode("element", "Supplier", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//roomAmenities"))
        {
            item.AppendChild(doc.CreateNode("element", "RoomAmenity", ""));
        }
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//RoomTypes"))
        {
            item.AppendChild(doc.CreateNode("element", "RoomType", ""));
        }
        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        hotelresp = JsonConvert.DeserializeObject<CXHotelInfo>(returnJson);

        //HotelInformationResponse hotelresp = new HotelInformationResponse();
        //hotelresp = hws.getInformation(hotelreq);

        if (hotelresp.HotelInformationResponse.HotelSummary != null && hotelresp.HotelInformationResponse.EanWsError == null)
        {
            lblHotelName.Text = hotelresp.HotelInformationResponse.HotelSummary.name;
            lblHotelAddress.Text = hotelresp.HotelInformationResponse.HotelSummary.address1 + " , " + hotelresp.HotelInformationResponse.HotelSummary.city + " , " + hotelresp.HotelInformationResponse.HotelSummary.countryCode
                + " , " + hotelresp.HotelInformationResponse.HotelSummary.postalCode;

            //lblPrice.Text = String.Format("{0:0.00}", hotelresp.HotelSummary.lowRate);

            string _hotelrating = hotelresp.HotelInformationResponse.HotelSummary.hotelRating.ToString();

            if (_hotelrating == "0")
            { btnRatings.CssClass = "rating-0"; }
            else if (_hotelrating == "1")
            { btnRatings.CssClass = "rating-1"; }
            else if (_hotelrating == "1.5")
            { btnRatings.CssClass = "rating-15"; }
            else if (_hotelrating == "2")
            { btnRatings.CssClass = "rating-2"; }
            else if (_hotelrating == "2.5")
            { btnRatings.CssClass = "rating-25"; }
            else if (_hotelrating == "3")
            { btnRatings.CssClass = "rating-3"; }
            else if (_hotelrating == "3.5")
            { btnRatings.CssClass = "rating-35"; }
            else if (_hotelrating == "4")
            { btnRatings.CssClass = "rating-4"; }
            else if (_hotelrating == "4.5")
            { btnRatings.CssClass = "rating-45"; }
            else if (_hotelrating == "5")
            { btnRatings.CssClass = "rating-5"; }


            if (hotelresp.HotelInformationResponse.HotelSummary.thumbNailUrl != null)
            {
                imgHotel.ImageUrl = hotelresp.HotelInformationResponse.HotelSummary.thumbNailUrl.ToString();
            }
            else
            {
                if (hotelresp.HotelInformationResponse.HotelImages != null)
                {
                    imgHotel.ImageUrl = hotelresp.HotelInformationResponse.HotelImages.HotelImage[0].thumbnailUrl.ToString();
                }

            }

            if (hotelresp.HotelInformationResponse.RoomTypes.RoomType != null)
            {

                //hotelresp.RoomTypes.RoomType.
                string roomtypeid = Request.QueryString["rtype"].ToString();

                foreach (CE.HotelEan.RoomType hotelroomtype in hotelresp.HotelInformationResponse.RoomTypes.RoomType)
                {
                    if (hotelroomtype.roomCode == roomtypeid)
                    {
                        lblRoomDetails.Text = hotelroomtype.description;

                        break;
                    }
                }
            }

        }
        else
        {
            lblMessage.Text = hotelresp.HotelInformationResponse.EanWsError.presentationMessage;
        }
    }

    protected void GetGuestDetails()
    {
        Int64 hotelsearchid = int.Parse(Session["hotelsearchid"].ToString());

        ExpediaHotelDB expdb = new ExpediaHotelDB();
        DataTable dtsearch = new DataTable();

        dtsearch = expdb.GetHotelSearchDetails(hotelsearchid);

        if (dtsearch.Rows.Count > 0)
        {
            lblCheckin.Text = Convert.ToDateTime(dtsearch.Rows[0]["arrivalDate"].ToString(), System.Globalization.CultureInfo.InvariantCulture).ToString("MMM dd, yyyy");
            lblCheckout.Text = Convert.ToDateTime(dtsearch.Rows[0]["departureDate"].ToString(), System.Globalization.CultureInfo.InvariantCulture).ToString("MMM dd, yyyy");

        }

        DataTable dtRoom = new DataTable();
        ExpediaHotelRoomDB exproomdb = new ExpediaHotelRoomDB();

        dtRoom = exproomdb.GetRoomDetails(hotelsearchid);

        if (dtRoom.Rows.Count > 0)
        {
            int NoOfRooms = dtRoom.Rows.Count;
            lblNoOfRooms.Text = NoOfRooms.ToString();

            int noOfAdults = 0;
            int noOfChild = 0;
            string occupants = "";

            for (int i = 0; i < NoOfRooms; i++)
            {
                noOfAdults = int.Parse(dtRoom.Rows[i]["NoOfAdults"].ToString()) + noOfAdults;
                noOfChild = int.Parse(dtRoom.Rows[i]["NoOfChildren"].ToString()) + noOfChild;

                if (dtRoom.Rows[i]["NoOfChildren"].ToString() != "0")
                {
                    occupants = dtRoom.Rows[i]["NoOfAdults"].ToString() + " Adults, " + dtRoom.Rows[i]["NoOfChildren"].ToString() + " Child";
                }
                else
                {
                    occupants = dtRoom.Rows[i]["NoOfAdults"].ToString() + " Adults";
                }

                if (i == 0)
                {
                    lblRoom1Occupants.Text = occupants;
                    inRoom1Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom1Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom1ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 1)
                {
                    lblRoom2Occupants.Text = occupants;
                    inRoom2Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom2Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom2ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 2)
                {
                    lblRoom3Occupants.Text = occupants;
                    inRoom3Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom3Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom3ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 3)
                {
                    lblRoom4Occupants.Text = occupants;
                    inRoom4Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom4Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom4ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 4)
                {
                    lblRoom5Occupants.Text = occupants;
                    inRoom5Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom5Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom5ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 5)
                {
                    lblRoom6Occupants.Text = occupants;
                    inRoom6Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom6Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom6ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 6)
                {
                    lblRoom7Occupants.Text = occupants;
                    inRoom7Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom7Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom7ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

                if (i == 7)
                {
                    lblRoom8Occupants.Text = occupants;
                    inRoom8Adults.Value = dtRoom.Rows[i]["NoOfAdults"].ToString();
                    inRoom8Child.Value = dtRoom.Rows[i]["NoOfChildren"].ToString();
                    inRoom8ChildAge.Value = dtRoom.Rows[i]["Info1"].ToString();
                }

            }

            if (noOfChild > 0)
            {
                lblOccupants.Text = noOfAdults.ToString() + " Adults, " + noOfChild.ToString() + " Children";
            }
            else
            {
                lblOccupants.Text = noOfAdults.ToString() + " Adults";
            }

            if (NoOfRooms >= 1)
            {
                divRoom1.Visible = true;
            }
            if (NoOfRooms >= 2)
            {
                divRoom2.Visible = true;
            }
            if (NoOfRooms >= 3)
            {
                divRoom3.Visible = true;
            }
            if (NoOfRooms >= 4)
            {
                divRoom4.Visible = true;
            }
            if (NoOfRooms >= 5)
            {
                divRoom5.Visible = true;
            }
            if (NoOfRooms >= 6)
            {
                divRoom6.Visible = true;
            }
            if (NoOfRooms >= 7)
            {
                divRoom7.Visible = true;
            }
            if (NoOfRooms >= 8)
            {
                divRoom8.Visible = true;
            }

        }

    }

    private void GetRoomAvailability()
    {
        Int64 hotelsearchid = int.Parse(Session["hotelsearchid"].ToString());
        ExpediaHotelDB expdb = new ExpediaHotelDB();
        DataTable dtsearch = new DataTable();

        dtsearch = expdb.GetHotelSearchDetails(hotelsearchid);

        if (dtsearch.Rows.Count > 0)
        {
            string chkin = "";
            string chkout = "";
            string checkindate = "";
            string checkoutdate = "";

            if (dtsearch.Rows[0]["arrivalDate"].ToString() != "1/1/1900 12:00:00 AM")
            {
                chkin = Convert.ToDateTime(dtsearch.Rows[0]["arrivalDate"].ToString(), System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
                chkout = Convert.ToDateTime(dtsearch.Rows[0]["departureDate"].ToString(), System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
            }

            if (chkin != "")
            {
                string[] checkinformatted = chkin.Split('/');
                checkindate = checkinformatted[1] + "-" + checkinformatted[0] + "-" + checkinformatted[2];

                string[] checkoutformatted = chkout.Split('/');
                checkoutdate = checkoutformatted[1] + "-" + checkoutformatted[0] + "-" + checkoutformatted[2];

                HotelRoomAvailabilityRequest roomavail = new HotelRoomAvailabilityRequest();
                roomavail.apiKey = _apikey;
                roomavail.cid = _cid;
                roomavail.minorRev = _minorrev;
                roomavail.minorRevSpecified = true;
                roomavail.customerIpAddress = Request.UserHostAddress;
                roomavail.customerUserAgent = Request.Browser.ToString();
                roomavail.customerSessionId = Session["customerSessionId"].ToString();
                roomavail.currencyCode = "SGD";
                roomavail.hotelId = int.Parse(Request.QueryString["hid"]);
                roomavail.arrivalDate = checkindate;
                roomavail.departureDate = checkoutdate;
                roomavail.locale = LocaleType.en_US;
                roomavail.includeDetails = true;
                roomavail.includeDetailsSpecified = true;
                roomavail.rateKey = Request.QueryString["rkey"].ToString();

                DataTable dtRoom = new DataTable();
                ExpediaHotelRoomDB exproomdb = new ExpediaHotelRoomDB();

                dtRoom = exproomdb.GetRoomDetails(hotelsearchid);

                string _strRoomXml = "";

                if (dtRoom.Rows.Count > 0)
                {
                    int iRoomCount = Convert.ToInt32(dtRoom.Rows.Count.ToString());
                    HotelWS.Room[] noofroom = new HotelWS.Room[iRoomCount];
                    for (int i = 0; i < iRoomCount; i++)
                    {
                        HotelWS.Room roomdtls = new HotelWS.Room();

                        roomdtls.numberOfAdults = int.Parse(dtRoom.Rows[i]["NoOfAdults"].ToString());
                        roomdtls.numberOfChildren = int.Parse(dtRoom.Rows[i]["NoOfChildren"].ToString());
                        roomdtls.numberOfChildrenSpecified = true;

                        noofroom[i] = roomdtls;

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + dtRoom.Rows[i]["NoOfAdults"].ToString() + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + dtRoom.Rows[i]["NoOfChildren"].ToString() + "</numberOfChildren>" +
                                    "<childAges>" + dtRoom.Rows[i]["info1"].ToString() + "</childAges>";
                        }
                        _strRoomXml += "</Room>";
                    }
                    roomavail.RoomGroup = noofroom;
                    roomavail.numberOfBedRooms = iRoomCount;
                    roomavail.numberOfBedRoomsSpecified = true;
                }

                roomavail.includeDetails = true;
                hotelAvailOption[] hotOptions = new hotelAvailOption[5];
                //hotelAvailOption roomtypes_opt = new hotelAvailOption();

                //roomtypes_opt = hotelAvailOption.ROOM_TYPES;
                //roomtypes_opt = hotelAvailOption.HOTEL_DETAILS;
                hotOptions[0] = hotelAvailOption.HOTEL_DETAILS;
                hotOptions[1] = hotelAvailOption.ROOM_TYPES;
                hotOptions[2] = hotelAvailOption.PROPERTY_AMENITIES;
                hotOptions[3] = hotelAvailOption.ROOM_AMENITIES;
                hotOptions[4] = hotelAvailOption.HOTEL_IMAGES;
                roomavail.options = hotOptions;

                //reformat date
                roomavail.arrivalDate = roomavail.arrivalDate.Replace("-", "/");
                roomavail.departureDate = roomavail.departureDate.Replace("-", "/");

                string getData = "http://api.ean.com/ean-services/rs/hotel/v3/avail?cid=" + roomavail.cid
                + "&minorRev=26&apiKey=" + roomavail.apiKey
                + "&locale=" + roomavail.locale
                + "&currencyCode=" + roomavail.currencyCode
                + "&customerIpAddress=" + roomavail.customerIpAddress
                + "&customerUserAgent=" + roomavail.customerUserAgent
                + "&_type=xml&customerSessionId=" + roomavail.customerSessionId
                + "&xml="
                + "<HotelRoomAvailabilityRequest><hotelId>" + roomavail.hotelId +
                "</hotelId><arrivalDate>" + roomavail.arrivalDate +
                "</arrivalDate><departureDate>" + roomavail.departureDate +
                "</departureDate><includeDetails>" + roomavail.includeDetails +
                "</includeDetails><numberOfBedRooms>" + roomavail.numberOfBedRooms +
                "</numberOfBedRooms><RoomGroup>" + _strRoomXml +
                "</RoomGroup><options>" + "HOTEL_DETAILS,ROOM_TYPES,PROPERTY_AMENITIES,ROOM_AMENITIES,HOTEL_IMAGES" +
                "</options>";

                getData += "</HotelRoomAvailabilityRequest>";

                CXHotelRoomAvail roomresponse = new CXHotelRoomAvail();

                // Handle JsonConvert array bug
                string returnJson = "";
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(getXMLResult(getData));
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//RateInfos"))
                {
                    item.AppendChild(doc.CreateNode("element", "RateInfo", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//Surcharges"))
                {
                    item.AppendChild(doc.CreateNode("element", "Surcharge", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//CancelPolicyInfoList"))
                {
                    item.AppendChild(doc.CreateNode("element", "CancelPolicyInfo", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//ValueAdds"))
                {
                    item.AppendChild(doc.CreateNode("element", "ValueAdd", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
                {
                    item.AppendChild(doc.CreateNode("element", "Supplier", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//BedTypes"))
                {
                    item.AppendChild(doc.CreateNode("element", "BedType", ""));
                }
                foreach (System.Xml.XmlNode item in doc.SelectNodes("//roomAmenities"))
                {
                    item.AppendChild(doc.CreateNode("element", "RoomAmenity", ""));
                }
                System.Xml.XmlElement root = doc.DocumentElement;
                root.AppendChild(doc.CreateNode("element", "HotelRoomResponse", ""));
                returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

                returnJson = returnJson.Replace("@", "");
                returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
                returnJson = returnJson.Replace("ns2:", "");
                roomresponse = JsonConvert.DeserializeObject<CXHotelRoomAvail>(returnJson);

                //HotelRoomAvailabilityResponse roomresponse = new HotelRoomAvailabilityResponse();
                //roomresponse = hws.getAvailability(roomavail);


                if (roomresponse != null && roomresponse.HotelRoomAvailabilityResponse.EanWsError == null)
                {
                    //BindRooms(roomresponse);
                    lblNotifications.Text = roomresponse.HotelRoomAvailabilityResponse.checkInInstructions;

                    if (roomresponse.HotelRoomAvailabilityResponse.HotelDetails != null)
                    {
                        lblHotelPolicy.Text = roomresponse.HotelRoomAvailabilityResponse.HotelDetails.hotelPolicy;
                    }

                    string roomtypeid = Request.QueryString["rtype"].ToString();
                    string roomcode = Request.QueryString["rcode"].ToString();

                    if (roomresponse.HotelRoomAvailabilityResponse.rateKey == null)
                    {
                        _ratekey = "";
                    }
                    else
                    {
                        _ratekey = roomresponse.HotelRoomAvailabilityResponse.rateKey;
                    }

                    foreach (CE.HotelEan.HotelRoomResponse roomresprow in roomresponse.HotelRoomAvailabilityResponse.HotelRoomResponse)
                    {
                        bool isRoomCheck = false;
                        _suppliertype = roomresprow.supplierType.ToString();

                        if (roomresprow.RoomType != null)
                        {
                            if (roomresprow.RoomType.roomCode == roomtypeid && roomresprow.rateCode == roomcode)
                            {
                                isRoomCheck = true;
                            }
                            
                        }
                        else //Agency or Venere
                        {
                            if (roomresprow.rateCode == roomcode) //roomTypeCode
                            {
                                isRoomCheck = true;
                                lblRoomDetails.Text = roomresprow.roomTypeDescription;

                                lblNotifications.Text = "<b>(Total hotel charges including taxes are billed at hotel.)</b> <br/><br/>";
                                lblNotifications.Text += "Important rate information  <br/>";
                                lblNotifications.Text += "* Room rate disclaimer: " + roomresprow.rateDescription + "<br/>";
                                lblNotifications.Text += "* The hotel requires a credit card guarantee for this room. <br/>";
                                lblNotifications.Text += "* The hotel can only guarantee this rate for 2 or less guests in this room. ";
                                lblNotifications.Text += "If there are more guests, additional charges may incur, or the property may advise an additional room. <br/>";

                                if (roomresprow.taxRate != null && roomresprow.taxRate != "")
                                {
                                    lblNotifications.Text += "* Note that this property usually charges taxes: " + roomresprow.taxRate + "<br/>";
                                }

                                lblNotifications.Text += "<br/>Rates quoted in Singapore dollars are based on current exchange rates, which may vary at time of travel. Final payment will be settled in local currency directly with the hotel.";

                                lblHotelPolicy.Text += "Requests for more than 2 people, or for more occupants than your selected rate indicates, will be sent to the hotel but are not guaranteed. If accepted, they will be subject to additional charges at the property's discretion.";
                            }
                        }

                        if (isRoomCheck)
                        {
                            if (roomresprow.RateInfos != null)
                            {
                                lblTaxService.Text = "";
                                bool hasHotelTax = false;
                                bool hasSalesTax = false;
                                float hoteltax = 0;
                                float salestax = 0;
                                float taxes = 0;
                                string chargedesc = "";
                                string currencycode = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode;

                                if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode == "SGD")
                                {
                                    if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges != null)
                                    {
                                        foreach (CE.HotelEan.Surcharge srow in roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.Surcharges.Surcharge)
                                        {
                                            chargedesc = srow.type.ToString();
                                            taxes = srow.amount;

                                            if (srow.type == CE.HotelEan.SurchargeType.ExtraPersonFee)
                                            {
                                                chargedesc = "Extra person fees";
                                                lblTaxService.Text += chargedesc + " " + currencycode + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.TaxAndServiceFee && _suppliertype == "E")
                                            {
                                                chargedesc = "Tax Recovery Charges and Service Fees";
                                                lblTaxService.Text += chargedesc + " " + currencycode + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.SalesTax)
                                            {
                                                chargedesc = "Sales Tax";
                                                hasSalesTax = true;
                                                salestax = srow.amount;
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.HotelOccupancyTax)
                                            {
                                                chargedesc = "Hotel Occupancy Tax";
                                                hasHotelTax = true;
                                                hoteltax = srow.amount;
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.ServiceFee)
                                            {
                                                chargedesc = "Service Fee";
                                                lblTaxService.Text += chargedesc + " " + currencycode + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";
                                            }

                                        }

                                        if (hasHotelTax && hasSalesTax)
                                        {
                                            lblTaxService.Text += "Hotel Occupancy and Sales Tax " + currencycode + " " + (string.Format("{0:0,0.00}", hoteltax + salestax)) + "<br/>";
                                        }
                                        else
                                        {
                                            if (hasHotelTax)
                                            {
                                                lblTaxService.Text += "Hotel Occupancy Tax " + currencycode + " " + (string.Format("{0:0,0.00}", hoteltax)) + "<br/>";
                                            }
                                            else if (hasSalesTax)
                                            {
                                                lblTaxService.Text += "Sales Tax " + currencycode + " " + (string.Format("{0:0,0.00}", salestax)) + "<br/>";
                                            }
                                        }
                                    }

                                    if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.totalSpecified)
                                    {
                                        lblTotalCharges.Text = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " + string.Format("{0:0,0.00}", roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.total);
                                        inputTotalCharge.Value = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.total.ToString();
                                    }
                                    else if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.nightlyRateTotalSpecified)
                                    {
                                        lblTotalCharges.Text = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " + string.Format("{0:0,0.00}", roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.nightlyRateTotal);
                                        inputTotalCharge.Value = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.nightlyRateTotal.ToString();
                                    }
                                    else if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRateSpecified)
                                    {
                                        lblTotalCharges.Text = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " + string.Format("{0:0,0.00}", roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate);
                                        inputTotalCharge.Value = roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate.ToString();
                                    }
                                   

                                    if (_suppliertype == "E")
                                    {
                                        lblTotalDesc.Text = "<br/>*includes tax recovery charges and service fees";
                                    }

                                    int RoomCount = int.Parse(lblNoOfRooms.Text);

                                    //float nightlyrate = 0;

                                    //foreach (NightlyRate nightrow in roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate)
                                    //{
                                    //    nightlyrate += nightrow.rate;
                                    //}

                                    //lblPriceDetails.Text = "";
                                    //for (int roomno = 1; roomno <= RoomCount; roomno++)
                                    //{
                                    //    string TotalCharge = string.Format("{0:0,0.00}", nightlyrate);

                                    //    lblPriceDetails.Text += "Room " + roomno.ToString() + "   " +
                                    //        roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " +
                                    //        TotalCharge + "<br/>";

                                    //}

                                    lblPriceDetails.Text = "";
                                    for (int roomno = 1; roomno <= RoomCount; roomno++)
                                    {
                                        lblPriceDetails.Text += "Room " + roomno.ToString() + " <br/>";

                                        int idays = 0;
                                        if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom != null)
                                        {
                                            foreach (CE.HotelEan.NightlyRate nightrow in roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.NightlyRatesPerRoom.NightlyRate)
                                            {
                                                string nightrate = string.Format("{0:0,0.00}", nightrow.rate);

                                                lblPriceDetails.Text += Convert.ToDateTime(roomresponse.HotelRoomAvailabilityResponse.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " +
                                                    nightrate + "<br/>";

                                                idays++;
                                            }
                                        }
                                        else if (roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRateSpecified)
                                        {
                                            lblPriceDetails.Text += Convert.ToDateTime(roomresponse.HotelRoomAvailabilityResponse.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.currencyCode + " " +
                                                                                               roomresprow.RateInfos.RateInfo[0].ChargeableRateInfo.maxNightlyRate + "<br/>";
                                        }

                                    }

                                    if (_suppliertype != "E")
                                    {
                                        lblPriceDetailsDesc.Text = "*excludes taxes and other surcharges imposed by the hotel. <br/>";
                                    }
                                    else if (_suppliertype == "E")
                                    {
                                        lblPriceDetailsDesc.Text = "*excluding tax recovery charges and service fees<br/>";
                                    }

                                    if (roomresprow.RateInfos.RateInfo[0].promo)
                                    {
                                        lblPromoDescription.Text = roomresprow.promoDescription + "<br/>";
                                        lblPromoDescription.ForeColor = System.Drawing.Color.OrangeRed;
                                    }
                                }
                                else
                                {
                                    currencycode = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode;

                                    if (roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges != null)
                                    {
                                        foreach (CE.HotelEan.Surcharge srow in roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.Surcharges.Surcharge)
                                        {
                                            chargedesc = srow.type.ToString();
                                            taxes = srow.amount;

                                            if (srow.type == CE.HotelEan.SurchargeType.ExtraPersonFee)
                                            {
                                                chargedesc = "Extra person fees";
                                                lblTaxService.Text += chargedesc + " " + currencycode + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.TaxAndServiceFee && _suppliertype == "E")
                                            {
                                                chargedesc = "Tax Recovery Charges and Service Fees";
                                                lblTaxService.Text += chargedesc + " " + currencycode + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.SalesTax)
                                            {
                                                chargedesc = "Sales Tax";
                                                hasSalesTax = true;
                                                salestax = srow.amount;
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.HotelOccupancyTax)
                                            {
                                                chargedesc = "Hotel Occupancy Tax";
                                                hasHotelTax = true;
                                                hoteltax = srow.amount;
                                            }

                                            if (srow.type == CE.HotelEan.SurchargeType.ServiceFee)
                                            {
                                                chargedesc = "Service Fee";
                                                lblTaxService.Text += chargedesc + " " + currencycode + " " + string.Format("{0:0,0.00}", taxes) + "<br/>";
                                            }

                                        }

                                        if (hasHotelTax && hasSalesTax)
                                        {
                                            lblTaxService.Text += "Hotel Occupancy and Sales Tax " + currencycode + " " + (string.Format("{0:0,0.00}", hoteltax + salestax)) + "<br/>";
                                        }
                                        else
                                        {
                                            if (hasHotelTax)
                                            {
                                                lblTaxService.Text += "Hotel Occupancy Tax " + currencycode + " " + (string.Format("{0:0,0.00}", hoteltax)) + "<br/>";
                                            }
                                            else if (hasSalesTax)
                                            {
                                                lblTaxService.Text += "Sales Tax " + currencycode + " " + (string.Format("{0:0,0.00}", salestax)) + "<br/>";
                                            }
                                        }
                                    }

                                    if (roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.totalSpecified)
                                    {
                                        lblTotalCharges.Text = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " + string.Format("{0:0,0.00}", roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.total);
                                        inputTotalCharge.Value = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.total.ToString();
                                    }
                                    else if (roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.nightlyRateTotalSpecified)
                                    {
                                        lblTotalCharges.Text = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " + string.Format("{0:0,0.00}", roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.nightlyRateTotal);
                                        inputTotalCharge.Value = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.nightlyRateTotal.ToString();
                                    }
                                    else if (roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRateSpecified)
                                    {
                                        lblTotalCharges.Text = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " + string.Format("{0:0,0.00}", roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate);
                                        inputTotalCharge.Value = roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate.ToString();
                                    }

                                    if (_suppliertype == "E")
                                    {
                                        lblTotalDesc.Text = "<br/>*includes tax recovery charges and service fees";
                                    }

                                    int RoomCount = int.Parse(lblNoOfRooms.Text);

                                    //int inight = 0;
                                    //float nightlyrate = 0;

                                    //foreach (NightlyRate nightrow in roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate)
                                    //{
                                    //    nightlyrate += nightrow.rate;
                                    //}

                                    //lblPriceDetails.Text = "";
                                    //for (int roomno = 1; roomno <= RoomCount; roomno++)
                                    //{
                                    //    string TotalCharge = string.Format("{0:0,0.00}", nightlyrate);

                                    //    lblPriceDetails.Text += "Room " + roomno.ToString() + "   " +
                                    //        roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " +
                                    //        TotalCharge + "<br/>";

                                    //}


                                    lblPriceDetails.Text = "";
                                    for (int roomno = 1; roomno <= RoomCount; roomno++)
                                    {
                                        lblPriceDetails.Text += "Room " + roomno.ToString() + " <br/>";

                                        int idays = 0;

                                        if (roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom != null)
                                        {
                                            foreach (CE.HotelEan.NightlyRate nightrow in roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.NightlyRatesPerRoom.NightlyRate)
                                            {
                                                string nightrate = string.Format("{0:0,0.00}", nightrow.rate);

                                                lblPriceDetails.Text += Convert.ToDateTime(roomresponse.HotelRoomAvailabilityResponse.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " +
                                                    nightrate + "<br/>";

                                                idays++;
                                            }
                                        }
                                        else if (roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate != null)
                                        {
                                            lblPriceDetails.Text += Convert.ToDateTime(roomresponse.HotelRoomAvailabilityResponse.arrivalDate, System.Globalization.CultureInfo.InvariantCulture).AddDays(idays).ToString("dd MMM yyyy") + " " + roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.currencyCode + " " +
                                                                                               roomresprow.RateInfos.RateInfo[0].ConvertedRateInfo.maxNightlyRate + "<br/>";
                                        }
                                    }

                                    if (_suppliertype != "E")
                                    {
                                        lblPriceDetailsDesc.Text = "<br/>*excludes taxes and other surcharges imposed by the hotel. <br/>";

                                        if (roomresprow.guaranteeRequired && !roomresprow.depositRequired)
                                        {
                                            _isPayAtHotel = true;
                                            lblCCdisclaimer.Text = "Credit card information is required in order for us to guarantee your reservation. Your credit card will not be charged until your arrival at the hotel or the cancellation deadline has passed.";
                                        }
                                        if (roomresprow.guaranteeRequired && roomresprow.depositRequired)
                                        {
                                            lblCCdisclaimer.Text = "Your credit card will be charged a deposit for your reservation. Your credit card will be charged directly by the hotel when your reservation is placed. ";
                                        }

                                    }
                                    else if (_suppliertype == "E")
                                    {
                                        lblPriceDetailsDesc.Text = "*excluding tax recovery charges and service fees<br/>";
                                    }

                                    if (roomresprow.RateInfos.RateInfo[0].promo)
                                    {
                                        lblPromoDescription.Text = roomresprow.promoDescription + "<br/>";
                                        lblPromoDescription.ForeColor = System.Drawing.Color.OrangeRed;
                                    }
                                }

                            }

                            lblCancellationPolicy.Text = roomresprow.RateInfos.RateInfo[0].cancellationPolicy;

                            if (roomresprow.supplierType == CE.HotelEan.SupplierType.E)
                            {
                                lblDisclaimer.Text = "By proceeding with this reservation, you agree to all terms and conditions, which include "
                                + "the Cancellation Policy and all terms and conditions contained in the "
                                + "<a href='http://travel.ian.com/index.jsp?pageName=userAgreement&locale=en_US&cid=381988' target='_blank'>User Agreement</a>. You agree to pay the cost "
                                + "of your reservation. If you do not pay this debt and it is collected through the use of a collection agency, "
                                + "an attorney, or through other legal proceedings, you agree to pay all reasonable costs or fees, including attorney "
                                + "fees and court costs, incurred in connection with such collection effort. ";

                            }

                            if (roomresprow.BedTypes != null)
                            {
                                if (roomresprow.BedTypes.size > 0 && roomresprow.BedTypes.BedType[0].description != "")
                                {
                                    divRoom1BeddingPref.Visible = true;
                                    divRoom2BeddingPref.Visible = true;
                                    divRoom3BeddingPref.Visible = true;
                                    divRoom4BeddingPref.Visible = true;
                                    divRoom5BeddingPref.Visible = true;
                                    divRoom6BeddingPref.Visible = true;
                                    divRoom7BeddingPref.Visible = true;
                                    divRoom8BeddingPref.Visible = true;
                                }

                                foreach (CE.HotelEan.bedType bedtyperow in roomresprow.BedTypes.BedType)
                                {
                                    ddlRoom1BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom2BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom3BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom4BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom5BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom6BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom7BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));
                                    ddlRoom8BeddingPref.Items.Add(new ListItem(bedtyperow.description, bedtyperow.id.ToString()));

                                }
                            }

                            if (roomresprow.smokingPreferences != null)
                            {
                                if (roomresprow.smokingPreferences.IndexOf(",") > 0)
                                {
                                    divRoom1SmokingPref.Visible = true;
                                    divRoom2SmokingPref.Visible = true;
                                    divRoom3SmokingPref.Visible = true;
                                    divRoom4SmokingPref.Visible = true;
                                    divRoom5SmokingPref.Visible = true;
                                    divRoom6SmokingPref.Visible = true;
                                    divRoom7SmokingPref.Visible = true;
                                    divRoom8SmokingPref.Visible = true;
                                }

                            }


                            break;
                        }
                    }

                }
                else
                {
                    //gvRooms.EmptyDataText = roomresponse.EanWsError.presentationMessage;
                    //gvRooms.DataBind();
                    lblMessage.Text = roomresponse.HotelRoomAvailabilityResponse.EanWsError.presentationMessage;
                }


            }
        }
    }

    private void GetPaymentType()
    {
        v3HotelPaymentRequest payrequest = new v3HotelPaymentRequest();
        payrequest.apiKey = _apikey;
        payrequest.cid = _cid;
        payrequest.minorRev = _minorrev;
        payrequest.customerIpAddress = Request.UserHostAddress;
        payrequest.customerUserAgent = Request.Browser.ToString();
        payrequest.customerSessionId = Session["customerSessionId"].ToString();
        payrequest.locale = LocaleType.en_US;
        payrequest.currencyCode = "SGD";

        string getData = "http://api.ean.com/ean-services/rs/hotel/v3/paymentInfo?cid=" + payrequest.cid
                + "&minorRev=26&apiKey=" + payrequest.apiKey
                + "&locale=" + payrequest.locale
                + "&currencyCode=" + payrequest.currencyCode
                + "&customerIpAddress=" + payrequest.customerIpAddress
                + "&customerUserAgent=" + payrequest.customerUserAgent
                + "&_type=xml&customerSessionId=" + payrequest.customerSessionId
                + "&xml="
                + "<HotelPaymentRequest>";

        getData += "</HotelPaymentRequest>";

        CXHotelPayment payresponse = new CXHotelPayment();

        // Handle JsonConvert array bug
        string returnJson = "";
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(getXMLResult(getData));
        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
        {
            item.AppendChild(doc.CreateNode("element", "Supplier", ""));
        }
        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

        returnJson = returnJson.Replace("@", "");
        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
        returnJson = returnJson.Replace("ns2:", "");
        payresponse = JsonConvert.DeserializeObject<CXHotelPayment>(returnJson);

        //HotelPaymentResponse payresponse = new HotelPaymentResponse();
        //payresponse = hws.getPaymentInfo(payrequest);

        if (payresponse != null)
        {
            foreach (CE.HotelEan.PaymentType paytypes in payresponse.HotelPaymentResponse.PaymentType)
            {
                ddlCardType.Items.Add(new ListItem(paytypes.name.ToUpper(), paytypes.code));
            }
        }

    }

    protected void btnContinue_Click(object sender, EventArgs e)
    {
        btnContinue.Enabled = false;
        divStep1Title.Visible = false;
        divStep2Title.Visible = true;

        divPaymentDetails.Visible = true;
        divGuestDetails.Visible = false;

        GetPaymentType();
    }

    protected void btnReserve_Click(object sender, EventArgs e)
    {
        ExpediaHotelBookingDB expbookingdb = new ExpediaHotelBookingDB();

        if (Request.QueryString["hid"] != null && Request.QueryString["rcode"] != null && Request.QueryString["rtype"] != null
            && Request.QueryString["rkey"] != null && Session["hotelsearchid"] != null && Session["customerSessionId"] != null)
        {
            Int64 sHotelSearchId = int.Parse(Session["hotelsearchid"].ToString());

            if (!expbookingdb.GetBookingDetailsBySearchId(sHotelSearchId))  //check if hotelsearchid is existing
            {

                btnReserve.Enabled = false;

                HotelBookingWS.HotelRoomReservationRequest roomreservationreq = new HotelBookingWS.HotelRoomReservationRequest();
                //HotelRoomReservationRequest roomreservationreq = new HotelRoomReservationRequest();
                roomreservationreq.apiKey = _apikey;
                roomreservationreq.cid = _cid;
                roomreservationreq.minorRev = _minorrev;
                roomreservationreq.customerIpAddress = Request.UserHostAddress;
                roomreservationreq.customerUserAgent = Request.Browser.ToString();
                roomreservationreq.customerSessionId = Session["customerSessionId"].ToString();
                roomreservationreq.locale = HotelBookingWS.LocaleType.en_US;
                roomreservationreq.currencyCode = "SGD";
                roomreservationreq.hotelId = int.Parse(Request.QueryString["hid"].ToString());
                roomreservationreq.arrivalDate = Convert.ToDateTime(lblCheckin.Text, System.Globalization.CultureInfo.InvariantCulture).ToString("MM/dd/yyyy");
                roomreservationreq.departureDate = Convert.ToDateTime(lblCheckout.Text, System.Globalization.CultureInfo.InvariantCulture).ToString("MM/dd/yyyy");
                roomreservationreq.rateCode = "";

                if (_suppliertype == "E")
                {
                    roomreservationreq.supplierType = HotelBookingWS.SupplierType.E;
                    roomreservationreq.roomTypeCode = Request.QueryString["rtype"].ToString();
                    roomreservationreq.rateCode = Request.QueryString["rcode"].ToString();
                }
                else if (_suppliertype == "S")
                {
                    roomreservationreq.supplierType = HotelBookingWS.SupplierType.S;
                    roomreservationreq.roomTypeCode = Request.QueryString["rcode"].ToString();
                    //roomreservationreq.rateCode = Request.QueryString["rcode"].ToString();
                }
                else if (_suppliertype == "V")
                {
                    roomreservationreq.supplierType = HotelBookingWS.SupplierType.V;
                    roomreservationreq.roomTypeCode = Request.QueryString["rcode"].ToString();
                }
                else if (_suppliertype == "W")
                {
                    roomreservationreq.supplierType = HotelBookingWS.SupplierType.W;
                    roomreservationreq.roomTypeCode = Request.QueryString["rcode"].ToString();
                }

                roomreservationreq.sendReservationEmail = true;
                roomreservationreq.rateKey = _ratekey; // Request.QueryString["rkey"].ToString();            
                roomreservationreq.chargeableRate = float.Parse(inputTotalCharge.Value.Trim());

                int totalAdult = 0;
                int totalChild = 0;
                int iRoomCount = Convert.ToInt32(lblNoOfRooms.Text);

                string _strRoomXml = "";

                HotelBookingWS.Room[] noofroom = new HotelBookingWS.Room[iRoomCount];
                for (int i = 0; i < iRoomCount; i++)
                {
                    HotelBookingWS.Room roomdtls = new HotelBookingWS.Room();

                    if (i == 0) //Room 1
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom1Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom1Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom1ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom1FirstName.Text;
                        roomdtls.lastName = txtRoom1LastName.Text;

                        if (divRoom1BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom1BeddingPref.SelectedValue;
                        }

                        if (divRoom1SmokingPref.Visible)
                        {
                            if (rdoRoom1SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom1SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom1SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";

                    }


                    if (i == 1) //Room 2
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom2Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom2Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom2ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom2FirstName.Text;
                        roomdtls.lastName = txtRoom2LastName.Text;

                        if (divRoom2BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom2BeddingPref.SelectedValue;
                        }

                        if (divRoom2SmokingPref.Visible)
                        {
                            if (rdoRoom2SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom2SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom2SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";
                    }

                    if (i == 2) //Room 3
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom3Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom3Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom3ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom3FirstName.Text;
                        roomdtls.lastName = txtRoom3LastName.Text;

                        if (divRoom3BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom3BeddingPref.SelectedValue;
                        }

                        if (divRoom3SmokingPref.Visible)
                        {
                            if (rdoRoom3SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom3SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom3SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";
                    }

                    if (i == 3) //Room 4
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom4Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom4Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom4ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom4FirstName.Text;
                        roomdtls.lastName = txtRoom4LastName.Text;

                        if (divRoom4BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom4BeddingPref.SelectedValue;
                        }

                        if (divRoom4SmokingPref.Visible)
                        {
                            if (rdoRoom4SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom4SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom4SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";
                    }

                    if (i == 4) //Room 5
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom5Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom5Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom5ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom5FirstName.Text;
                        roomdtls.lastName = txtRoom5LastName.Text;

                        if (divRoom5BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom5BeddingPref.SelectedValue;
                        }

                        if (divRoom5SmokingPref.Visible)
                        {
                            if (rdoRoom5SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom5SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom5SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";
                    }

                    if (i == 5) //Room 6
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom6Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom6Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom6ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom6FirstName.Text;
                        roomdtls.lastName = txtRoom6LastName.Text;

                        if (divRoom6BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom6BeddingPref.SelectedValue;
                        }

                        if (divRoom6SmokingPref.Visible)
                        {
                            if (rdoRoom6SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom6SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom6SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";
                    }

                    if (i == 6) //Room 7
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom7Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom7Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom7ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom7FirstName.Text;
                        roomdtls.lastName = txtRoom7LastName.Text;

                        if (divRoom7BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom7BeddingPref.SelectedValue;
                        }

                        if (divRoom7SmokingPref.Visible)
                        {
                            if (rdoRoom7SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom7SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom7SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";
                    }

                    if (i == 7) //Room 8
                    {
                        roomdtls.numberOfAdults = int.Parse(inRoom8Adults.Value);
                        roomdtls.numberOfChildren = int.Parse(inRoom8Child.Value);

                        if (roomdtls.numberOfChildren > 0)
                        {
                            int[] iChildages = new int[roomdtls.numberOfChildren];
                            string[] sChildages = inRoom8ChildAge.Value.Split(',');

                            for (int ages = 0; ages < roomdtls.numberOfChildren; ages++)
                            {
                                iChildages[ages] = int.Parse(sChildages[ages].ToString().Trim());

                            }
                            roomdtls.childAges = iChildages;
                        }

                        roomdtls.firstName = txtRoom8FirstName.Text;
                        roomdtls.lastName = txtRoom8LastName.Text;

                        if (divRoom8BeddingPref.Visible)
                        {
                            roomdtls.bedTypeId = ddlRoom8BeddingPref.SelectedValue;
                        }

                        if (divRoom8SmokingPref.Visible)
                        {
                            if (rdoRoom8SmokingPref.SelectedValue == "E")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.E;
                            }
                            if (rdoRoom8SmokingPref.SelectedValue == "NS")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.NS;
                            }
                            if (rdoRoom8SmokingPref.SelectedValue == "S")
                            {
                                roomdtls.smokingPreference = HotelBookingWS.SmokingPreference.S;
                            }
                        }

                        _strRoomXml += "<Room>" +
                            "<numberOfAdults>" + roomdtls.numberOfAdults + "</numberOfAdults>";
                        if (roomdtls.numberOfChildren > 0)
                        {
                            _strRoomXml += "<numberOfChildren>" + roomdtls.numberOfChildren + "</numberOfChildren>" +
                                    "<childAges>" + roomdtls.numberOfChildren + "</childAges>";
                        }
                        _strRoomXml += "<firstName>" + roomdtls.firstName + "</firstName>";
                        _strRoomXml += "<lastName>" + roomdtls.lastName + "</lastName>";
                        _strRoomXml += "<bedTypeId>" + roomdtls.bedTypeId + "</bedTypeId>";
                        _strRoomXml += "<smokingPreference>" + roomdtls.smokingPreference.ToString() + "</smokingPreference>";
                        _strRoomXml += "</Room>";

                    }

                    totalAdult = roomdtls.numberOfAdults + totalAdult;
                    totalChild = roomdtls.numberOfChildren + totalChild;

                    noofroom[i] = roomdtls;
                }

                roomreservationreq.RoomGroup = noofroom;

                roomreservationreq.ReservationInfo = new HotelBookingWS.reservationInfo();

                roomreservationreq.ReservationInfo.email = txtEmailAddress.Text;
                roomreservationreq.ReservationInfo.firstName = txtCardholderFirstName.Text;
                roomreservationreq.ReservationInfo.lastName = txtCardholderLastName.Text;
                roomreservationreq.ReservationInfo.homePhone = txtPhoneNumber.Text;
                roomreservationreq.ReservationInfo.workPhone = txtPhoneNumber.Text;

                roomreservationreq.ReservationInfo.creditCardType = ddlCardType.SelectedValue;
                roomreservationreq.ReservationInfo.creditCardNumber = txtCardNumber.Text.Trim();
                roomreservationreq.ReservationInfo.creditCardIdentifier = txtSecurityCode.Text.Trim();
                roomreservationreq.ReservationInfo.creditCardExpirationMonth = ddlMonthExpiration.SelectedValue;
                roomreservationreq.ReservationInfo.creditCardExpirationYear = ddlYearExpiration.SelectedValue;

                roomreservationreq.AddressInfo = new HotelBookingWS.addressInfo();
                //testing
                //roomreservationreq.AddressInfo.address1 = "travelnow";

                roomreservationreq.AddressInfo.address1 = txtAddress1.Text;
                //roomreservationreq.AddressInfo.address2 = txtAddress2.Text;

                roomreservationreq.AddressInfo.city = txtCity.Text.Trim();
                roomreservationreq.AddressInfo.countryCode = ddlCountry.SelectedValue;
                roomreservationreq.AddressInfo.postalCode = txtPostal.Text;

                //save to cxtable
                ExpediaHotelBookingInfo expbooking = new ExpediaHotelBookingInfo();

                expbooking.HotelSearchID = sHotelSearchId;
                expbooking.Email = txtEmailAddress.Text.Trim();
                expbooking.FirstName = txtRoom1FirstName.Text.Trim();
                expbooking.LastName = txtRoom1LastName.Text.Trim();
                expbooking.CustomerSessionId = Session["customerSessionId"].ToString();
                expbooking.ArrivalDate = Convert.ToDateTime(lblCheckin.Text, System.Globalization.CultureInfo.InvariantCulture);
                expbooking.DepartureDate = Convert.ToDateTime(lblCheckout.Text, System.Globalization.CultureInfo.InvariantCulture);
                expbooking.NoOfRooms = iRoomCount;
                expbooking.NoOfAdults = totalAdult;
                expbooking.NoOfChild = totalChild;
                expbooking.HotelID = int.Parse(Request.QueryString["hid"].ToString());
                expbooking.HotelName = lblHotelName.Text;
                expbooking.RateKey = _ratekey; // Request.QueryString["rkey"].ToString();
                expbooking.RoomTypeCode = Request.QueryString["rtype"].ToString();
                expbooking.RateCode = Request.QueryString["rcode"].ToString();
                expbooking.SupplierType = _suppliertype;
                expbooking.ChargeableRate = float.Parse(inputTotalCharge.Value.Trim()); ;
                expbooking.Address = txtAddress1.Text;
                expbooking.CountryCode = ddlCountry.SelectedValue;
                expbooking.PostalCode = txtPostal.Text;
                expbooking.Info1 = _isPayAtHotel.ToString();

                Int64 bookingId = expbookingdb.Insert(expbooking);

                if (bookingId > 0)
                {
                    DataTable dtBooking = new DataTable();
                    dtBooking = expbookingdb.GetBookingDetails(bookingId);

                    if (dtBooking.Rows.Count > 0)
                    {
                        roomreservationreq.affiliateConfirmationId = dtBooking.Rows[0]["HotelBookingGUID"].ToString();
                        roomreservationreq.affiliateCustomerId = bookingId.ToString();

                        string _strReservationInfoXml = "", _strAddressInfoXml = "";

                        _strReservationInfoXml += "<email>" + roomreservationreq.ReservationInfo.email + "</email>";
                        _strReservationInfoXml += "<firstName>" + roomreservationreq.ReservationInfo.firstName + "</firstName>";
                        _strReservationInfoXml += "<lastName>" + roomreservationreq.ReservationInfo.lastName + "</lastName>";
                        _strReservationInfoXml += "<homePhone>" + roomreservationreq.ReservationInfo.homePhone + "</homePhone>";
                        _strReservationInfoXml += "<workPhone>" + roomreservationreq.ReservationInfo.workPhone + "</workPhone>";
                        _strReservationInfoXml += "<creditCardType>" + roomreservationreq.ReservationInfo.creditCardType + "</creditCardType>";
                        _strReservationInfoXml += "<creditCardNumber>" + roomreservationreq.ReservationInfo.creditCardNumber + "</creditCardNumber>";
                        _strReservationInfoXml += "<creditCardExpirationMonth>" + roomreservationreq.ReservationInfo.creditCardExpirationMonth + "</creditCardExpirationMonth>";
                        _strReservationInfoXml += "<creditCardExpirationYear>" + roomreservationreq.ReservationInfo.creditCardExpirationYear + "</creditCardExpirationYear>";
                        _strReservationInfoXml += "<creditCardIdentifier>" + roomreservationreq.ReservationInfo.creditCardIdentifier + "</creditCardIdentifier>";

                        _strAddressInfoXml += "<address1>" + roomreservationreq.AddressInfo.address1 + "</address1>";
                        _strAddressInfoXml += "<city>" + roomreservationreq.AddressInfo.city + "</city>";
                        _strAddressInfoXml += "<countryCode>" + roomreservationreq.AddressInfo.countryCode + "</countryCode>";
                        _strAddressInfoXml += "<postalCode>" + roomreservationreq.AddressInfo.postalCode + "</postalCode>";

                        string getData = "https://book.api.ean.com/ean-services/rs/hotel/v3/res?cid=" + roomreservationreq.cid
                + "&minorRev=26&apiKey=" + roomreservationreq.apiKey
                + "&locale=" + roomreservationreq.locale
                + "&currencyCode=" + roomreservationreq.currencyCode
                + "&customerIpAddress=" + roomreservationreq.customerIpAddress
                + "&customerUserAgent=" + roomreservationreq.customerUserAgent
                + "&_type=xml&customerSessionId=" + roomreservationreq.customerSessionId
                + "&xml="
                + "<HotelRoomReservationRequest><hotelId>" + roomreservationreq.hotelId +
                "</hotelId><arrivalDate>" + roomreservationreq.arrivalDate +
                "</arrivalDate><departureDate>" + roomreservationreq.departureDate +
                "</departureDate><supplierType>" + roomreservationreq.supplierType.ToString() +
                "</supplierType><roomTypeCode>" + roomreservationreq.roomTypeCode +
                "</roomTypeCode><rateCode>" + roomreservationreq.rateCode +
                "</rateCode><chargeableRate>" + roomreservationreq.chargeableRate +
                "</chargeableRate><affiliateCustomerId>" + roomreservationreq.affiliateCustomerId +
                "</affiliateCustomerId><affiliateConfirmationId>" + roomreservationreq.affiliateConfirmationId +
                "</affiliateConfirmationId><RoomGroup>" + _strRoomXml +
                "</RoomGroup><ReservationInfo>" + _strReservationInfoXml +
                "</ReservationInfo><AddressInfo>" + _strAddressInfoXml +
                "</AddressInfo>";

                        if (roomreservationreq.rateKey != "")
                            getData += "<rateKey>" + roomreservationreq.rateKey + "</rateKey>";

                        getData += "</HotelRoomReservationRequest>";

                        CXHotelRoomReservation roomreservationresp = new CXHotelRoomReservation();

                        // Handle JsonConvert array bug
                        string returnJson = "";
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        
                        doc.LoadXml(getXMLResultPOST(getData));
                        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Suppliers"))
                        {
                            item.AppendChild(doc.CreateNode("element", "Supplier", ""));
                        }
                        foreach (System.Xml.XmlNode item in doc.SelectNodes("//roomAmenities"))
                        {
                            item.AppendChild(doc.CreateNode("element", "RoomAmenity", ""));
                        }
                        foreach (System.Xml.XmlNode item in doc.SelectNodes("//RateInfos"))
                        {
                            item.AppendChild(doc.CreateNode("element", "RateInfo", ""));
                        }
                        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Discounts"))
                        {
                            item.AppendChild(doc.CreateNode("element", "Discount", ""));
                        }
                        foreach (System.Xml.XmlNode item in doc.SelectNodes("//Surcharges"))
                        {
                            item.AppendChild(doc.CreateNode("element", "Surcharge", ""));
                        }
                        System.Xml.XmlElement root = doc.DocumentElement;
                        root.AppendChild(doc.CreateNode("element", "confirmationNumbers", ""));
                        returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");

                        returnJson = returnJson.Replace("@", "");
                        returnJson = returnJson.Replace("\"xmlns:ns2\":\"http://v3.hotel.wsapi.ean.com/\",", "");
                        returnJson = returnJson.Replace("ns2:", "");
                        roomreservationresp = JsonConvert.DeserializeObject<CXHotelRoomReservation>(returnJson);

                        //HotelBookingWS.HotelRoomReservationResponse roomreservationresp = new HotelBookingWS.HotelRoomReservationResponse();
                        //roomreservationresp = hbookingws.getReservation(roomreservationreq);

                        if (roomreservationresp != null && roomreservationresp.HotelRoomReservationResponse.EanWsError == null)
                        {
                            if (roomreservationresp.HotelRoomReservationResponse.processedWithConfirmation && roomreservationresp.HotelRoomReservationResponse.reservationStatusCode == "CF")
                            {
                                string confirmationnos = "";

                                for (int inum = 0; inum < roomreservationresp.HotelRoomReservationResponse.confirmationNumbers.Length; inum++)
                                {
                                    if (inum == 0)
                                    {
                                        confirmationnos = roomreservationresp.HotelRoomReservationResponse.confirmationNumbers[inum].ToString();
                                    }
                                    else
                                    {
                                        confirmationnos = confirmationnos + "," + roomreservationresp.HotelRoomReservationResponse.confirmationNumbers[inum].ToString();
                                    }
                                }

                                //roomreservationresp.confirmationNumbers
                                Int64 iUpdate = expbookingdb.Confirm(bookingId, roomreservationresp.HotelRoomReservationResponse.itineraryId.ToString(), confirmationnos, roomreservationresp.HotelRoomReservationResponse.reservationStatusCode);

                                if (iUpdate > 0)
                                {
                                    Response.Redirect("confirmation.aspx?bid=" + bookingId.ToString() + "&itid=" + roomreservationresp.HotelRoomReservationResponse.itineraryId.ToString());
                                    //lblMessage.Text = "success!";
                                }
                            }

                        }
                        else
                        {
                            lblMessage.Text = roomreservationresp.HotelRoomReservationResponse.EanWsError.presentationMessage; // +" - " + roomreservationresp.EanWsError.verboseMessage.ToString();
                            expbookingdb.UpdateErrMessage(bookingId, lblMessage.Text);
                        }
                    }
                    else
                    {
                        lblMessage.Text = "booking details not saved";
                    }
                }
            }
            else
            {
                lblMessage.Text = "A booking has already been made with this session/id. Please <a href='../hotels-search.aspx' alt='' >click here</a> to search again.";
                btnReserve.Enabled = false;
            }
        }
        else
        {
            Response.Redirect("../hotels-search.aspx");
        }
    }
    private string getXMLResult(string requestData)
    {
        WebRequest request = null;
        request = WebRequest.Create(requestData);
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        responseFromServer = responseFromServer.Replace("@", "");
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }
    private string getXMLResultPOST(string requestData)
    {
        var request = WebRequest.Create(requestData);
        request.Method = "POST";
        string postData = requestData;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentType = "application/xml";
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        var response = request.GetResponse();
        var responseCode = (((HttpWebResponse)response).StatusDescription);

        Stream responseStream = response.GetResponseStream();
        var responseReader = new StreamReader(responseStream, Encoding.UTF8);
        string responseFromServer = responseReader.ReadToEnd();

        return responseFromServer;
    }
}
